﻿
//==============================================================================
// 文件     ：Win32.cs
// 功能概要 ：封装win32 API
//           
//           
// 作者    ：周薇
// 时间    ：2011年5月16日
// Copyright (c) 2011 重庆安运科技公司. All rights reserved.
//==============================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;

namespace Webcar.Utils
{
    public static class Win32
    {
        static long freq = 0;
        static Win32()
        {
            QueryPerformanceFrequency(out freq);
        }
        [DllImport("Kernel32.dll")]
        public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        public static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetShortPathName(
            [MarshalAs(UnmanagedType.LPTStr)]string lpszLongPath,
            [MarshalAs(UnmanagedType.LPTStr)]StringBuilder lpszShortPath,
            int cchBuffer);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetLongPathName(
                 [MarshalAs(UnmanagedType.LPTStr)]
                   string path,
                 [MarshalAs(UnmanagedType.LPTStr)]
                   StringBuilder longPath,
                 int longPathLength
                 );
        [DllImport("Kernel32.dll")]
        public static extern void SetLocalTime(SystemTime st);

        [StructLayout(LayoutKind.Sequential)]
        public class SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort Whour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }

        public static void SetSystemTime(DateTime now)
        {
            SystemTime st = new SystemTime();
            st.wYear = (ushort)now.Year;
            st.wMonth = (ushort)now.Month;
            st.wDay = (ushort)now.Day;
            st.Whour = (ushort)now.Hour;
            st.wMinute = (ushort)now.Minute;
            st.wSecond = (ushort)now.Second;
            SetLocalTime(st);
        }
        /// <summary>
        /// 取得8.3文件名
        /// </summary>
        /// <param name="longName">长文件名</param>
        /// <returns></returns>
        public static string ToShortPathName(string longName)
        {
            int bufferSize = 256;
            StringBuilder shortNameBuffer = new StringBuilder(bufferSize);

            int result = GetShortPathName(longName, shortNameBuffer, bufferSize);

            return shortNameBuffer.ToString().IsNull() ? longName : shortNameBuffer.ToString();
        }
        [DllImport("Kernel32.dll", EntryPoint = "Beep")]
        public static extern int Beep(int dwFreq, int dwDuration);

        /// <summary>
        /// 高精度Sleep CPU占用较高
        /// </summary>
        /// <param name="delayTime">毫秒</param>
        public static void Delay(int delayTime)
        {
            long start = 0;
            long stop = 0;

            QueryPerformanceCounter(out start);
            while (true)
            {
                QueryPerformanceCounter(out stop);
                long interval = 1000 * (stop - start) / freq;
                if (interval >= delayTime) break;
            }
        }
        [DllImport("winmm.dll")]
        private static extern uint timeBeginPeriod(uint period);

        [DllImport("winmm.dll")]
        private static extern uint timeEndPeriod(uint period);
        [DllImport("winmm.dll")]
        private static extern long waveOutSetVolume(uint deviceID, uint Volume);
        [DllImport("winmm.dll")]
        private static extern long waveOutGetNumDevs();


        [DllImport("winmm.dll")]
        private static extern uint waveOutGetVolume(IntPtr deviceID, out   uint Volume);
        /// <summary>
        /// 得到系统声音大小
        /// </summary>
        /// <returns></returns>
        public static uint GetSystemVolume()
        {

            IntPtr p = new IntPtr(0);
            uint v = 0;
            waveOutGetVolume(p, out   v);


            ushort CalcVol = (ushort)(v & 0x0000ffff);

            //uint vleft = v & 0xFFFF;
            //uint vright = (v & 0xFFFF0000) >> 16;
            return CalcVol;
        }
        /// <summary>
        /// 设置系统声音大小
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        public static void SetSystemVolume(uint left, uint right)
        {
            //uint v = left << 16 | right;
            uint v = ((left & 0x0000ffff) | (right << 16));
            waveOutSetVolume(0, v);
        }
        /// <summary>
        /// sleep,精度1毫秒
        /// </summary>
        /// <param name="i"></param>
        public static void Sleep(int i)
        {
            Win32.timeBeginPeriod(1);
            Thread.Sleep(i);
            Win32.timeEndPeriod(1);
        }

        [DllImport("Ws2_32.dll")]
        public static extern uint inet_addr(string ip);
        [DllImport("Ws2_32.dll")]
        public static extern uint htonl(uint hostlong);
        [DllImport("Ws2_32.dll")]
        public static extern uint ntohl(uint netlong);
        [DllImport("Ws2_32.dll")]
        public static extern ushort htons(ushort hostlong);
        [DllImport("Ws2_32.dll")]
        public static extern ushort ntohs(ushort netlong);

        [DllImport("imm32.dll")]
        public static extern IntPtr ImmGetContext(IntPtr hWnd);
        [DllImport("imm32.dll")]
        public static extern bool ImmGetConversionStatus(IntPtr hIMC,
            ref int conversion, ref int sentence);

        /// <summary>
        /// 该函数设置由不同线程产生的窗口的显示状态。
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表，请查阅ShowWindow函数的说明部分。</param>
        /// <returns>如果函数原来可见，返回值为非零；如果函数原来被隐藏，返回值为零。</returns>
        [DllImport("User32.dll")]
        public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

        /// <summary>
        /// 该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零。</returns>
        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        public const int SW_HIDE = 0;
        public const int SW_SHOWNORMAL = 1;
        public const int SW_SHOWMINIMIZED = 2;
        public const int SW_SHOWMAXIMIZED = 3;
        public const int SW_SHOWNOACTIVATE = 4;
        public const int SW_RESTORE = 9;
        public const int SW_SHOWDEFAULT = 10;
        [DllImport("User32")]
        public static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
        //[DllImport("User32")]
        //public static extern int MessageBeep(uint uType);
        //public const uint Ok = 0x00000000;
        //public const uint Error = 0x00000010;
        //public const uint Question = 0x00000020;
        //public const uint Warning = 0x00000030;
        //public const uint Information = 0x00000040;
        const uint SPI_SETSCREENSAVEACTIVE = 0x0011;

        [System.Runtime.InteropServices.DllImport("User32")]
        extern static bool SystemParametersInfoW(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);

        public static void DisableScreenSaver()
        {
            SystemParametersInfoW(SPI_SETSCREENSAVEACTIVE, 0, IntPtr.Zero, 0);  //禁用
            //SystemParametersInfoW(SPI_SETSCREENSAVEACTIVE, 1, IntPtr.Zero, 0);  //启用
        }

        private const int INTERNET_CONNECTION_MODEM = 1;

        private const int INTERNET_CONNECTION_LAN = 2;

        [DllImport("winInet.dll")]
        private static extern bool InternetGetConnectedState(ref   int dwFlag, int dwReserved);

        public static bool IsInternetAvaible()
        {
            System.Int32 dwFlag = new int();
            return InternetGetConnectedState(ref   dwFlag, 0);
        }

    }
}
